<?php
/**
 * Определение языка с помощью Google Translate API
 * Language detection using Google Translate API
 *
 * @author Чекальский Илья, Chekalskiy Ilya
 * @example lang_detect::detect('Hello, world!');
 * @version 2.0
 */
class lang_detect {
	/**
	 * @var integer CURL-timeout
	 */
	private static $timeout = 4;
	/**
	 * @var string google api url
	 */
	private static $google_url = "https://www.googleapis.com/language/translate/v2/detect";

    /**
	 * Working with HTTP-query
	 * @param string $url URL
	 * @return string Content
	 */
	private function http($url) {
		$useragent = 'Lang Detection Class v2 by ilya@chekalskiy.ru';

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
		curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$timeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, self::$timeout);

		$result = curl_exec($ch);
		if (curl_error($ch)) throw new LangDetectException('CURL Error: '.curl_error($ch));
		curl_close($ch);
		
		return $result;
	}

	/**
	 * Detect language
	 * @param string $text Text
	 * @param string $key Google API Key - You can get it at http://code.google.com/apis/console
	 * @return string language code
	 */
	public static function detect($text, $key = '') {
		if (!is_string($text) && $text == '') { throw new LangDetectException('Detect error: $text is empty'); return false; }
		if (strlen($text) >= 255) { $text = mb_substr($text, 0, 254, 'UTF-8'); }

		$query = rawurlencode($text);
		$url = self::$google_url . '?key=' . $key .'&q=' . $query;
		$googleresponse = self::http($url);

		$response = json_decode($googleresponse, true);
		if (isset($response['error'])) throw new LangDetectException($response['error']['message'], $response['error']['code']); return false;
		return $response['data']['detections'][0][0]['language'];
	}
}

class LangDetectException extends Exception {}
?>
